import React, { useEffect, useReducer } from 'react';
import './App.less';
import Spinning from '@/platform/components/spinning/Spinning';
import http from '@/platform/commons/utils/axios-util';
import { useHistory, useLocation } from 'react-router-dom';
import IndividuationUtil from '@/platform/commons/utils/individuation-util';
import renderRoutes from '@/platform/components/render-routes/RenderRoutes';
import { spinningInitialState, spinningReducer } from '@/platform/reducers/spinning-reducer';
import AppContext from '@/platform/contexts/app-context';
import registerHttpInterceptor from '@/shared/interceptors/http-interceptors';
import SysStorageUtils from './platform/commons/utils/sys-storage-util';
import Environments from './platform/commons/utils/env-util';


let httpInterceptorInstance:any = null;

const App:React.FC<{route:any}> = ({ route }:any) => {
    const location = useLocation();
    const history = useHistory();
    const [spinningState, dispatchSpinningState] = useReducer(spinningReducer, spinningInitialState);
     

    if (null === httpInterceptorInstance) {
        httpInterceptorInstance = registerHttpInterceptor(http, history, dispatchSpinningState);
    }
   
    useEffect(() => {
        IndividuationUtil.initAppTheme();
    }, []);

    useEffect(() => {
        if (location.pathname === '/') {
            const sessionUser = SysStorageUtils.getSessionUser();
            const replaceRouter = sessionUser ? Environments.getEvnProp('REACT_APP_HOME_ROUTER') : Environments.getEvnProp('REACT_APP_LOGIN_ROUTER');
            history.replace(replaceRouter);
        }
    }, [location.pathname]);
    
    return (
        <AppContext.Provider value={{
            dispatchSpinningState
        }}
        >
            <Spinning visible={spinningState.visible} />
            { renderRoutes(route.routes) }
        </AppContext.Provider>
    )
};

export default App;
